﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Pixels.Core
{
    internal class PixelSerializableHelper
    {     
        public static object DeserializeObject(String pXmlizedString)
        {
            NetDataContractSerializer xs = new NetDataContractSerializer();
            MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(pXmlizedString));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            return xs.Deserialize(memoryStream);
        }

        private static Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }

        public static String SerializeObject(object Object)
        {
            try
            {
                String XmlizedString = null;
                MemoryStream memoryStream = new MemoryStream();
                NetDataContractSerializer xs = new NetDataContractSerializer();
                xs.Serialize(memoryStream, Object);
                memoryStream.Position = 0;
                XmlizedString = System.Convert.ToBase64String(memoryStream.ToArray());
                return XmlizedString;
            }
            catch (Exception e) { System.Console.WriteLine(e); return null; }
        }

        private static String UTF8ByteArrayToString(Byte[] characters)
        {

            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }     
    }
}
